<template>
	<view class="app-container">
		<z-paging ref="paging" v-model="recordList" @query="queryList">
			<template #top>
				<view style="background-color: var(--tn-color-primary);">
					<tn-navbar  home-icon=""  bg-color="tn-type-primary_bg" text-color="tn-white">合单发货</tn-navbar>
				</view>
				<!-- 搜索框 -->
				<view class="search-section">
					<tn-search-box
						v-model="searchKeyword"
						placeholder="请输入检索条件"
						:show-action="false"
						:clearable="true"
						@search="handleSearch"
						@clear="handleClear"
						size="sm"
					></tn-search-box>
					
					<view class="date-range tn-p tn-text-xl tn-white_bg" @click="openCalendarPopup">
						<view class="date-picker-title">
							<tn-icon name="calendar" size="32" color="#666666"></tn-icon>
							<text class="picker-text">时间选择</text>
						</view>
						<text class="date-text">{{dataInfo.startDate}} 至 {{dataInfo.endDate}}</text>
					</view>
				</view>
			</template>
			
			<!-- 记录列表 -->
			<view class="record-list">
				<view class="record-item" v-for="(item, index) in recordList" :key="index">
					<view class="record-header">
						<view class="checkbox-wrapper">
							<tn-checkbox
								v-model="item.sel"
								@change="handleCheckboxChange"
								:active-value="1" :inactive-value="0"
							></tn-checkbox>
						</view>
						<view class="order-info">
							<view class="order-top">
								<view class="order-left">
									<text class="agent-name">{{item.orgname}}</text>
									<text class="order-time">{{item.dates}}</text>
								</view>
								<view class="order-right">
									<text class="order-amount">¥{{item.taxamount}}</text>
								</view>
							</view>
							<view class="order-middle">
								<view class="order-no">
									<text class="label">订单号：</text>
									<text class="value">{{item.billcode}}</text>
								</view>
								<view class="product-count">
									<text class="label">商品数量：</text>
									<text class="value">{{item.goodscount}}</text>
								</view>
							</view>
							<view class="order-customer">
								<text class="label">客户：</text>
								<text class="value">{{item.businessname}}</text>
							</view>
							<view class="order-address">
								<text class="value">{{item.billinfo}}</text>
							</view>
							<!-- Add view details button -->
							<view class="order-actions">
								<tn-button  @click="showDetails(item)">查看明细</tn-button>
							</view>
						</view>
					</view>
				</view>
			</view>
            <template #bottom>
                <!-- 底部操作栏 -->
                <view class="bottom-bar">
                    <view class="selected-info">
                        已选择 {{selectedCount}} 项
                    </view>
                    <view class="action-buttons">
                        <tn-button
                            type="primary"
                            @click="showShippingForm"
                            :disabled="!canShip"
                        >
                            单据下发
                        </tn-button>
                    </view>
                </view>
            </template>
		</z-paging>
		
		
	</view>
	
	<tn-popup v-model="showCalendarPopup" open-direction="top" class="popup-class">
		<tn-calendar v-model="selectDate" min-date="2024-01-01" mode="range" class="calendar-class tn-mt-xl tn-pt-xl"/>
		<view class="tn-mt tn-w-full tn-pb">
			<tn-button
				font-size="36"
				custom-class="popup-calendar-button"
				@click="closeCalendarPopupPage"
			>
				选择所选日期
			</tn-button>
		</view>
	</tn-popup>
	
	<!-- 收货信息弹出层 -->
	<tn-popup v-model="showShippingPopup" mode="center">
		<view class="shipping-form">
			<view class="form-title">收货信息</view>
			<view class="form-item">
				<text class="label">收货人</text>
				<tn-input
					v-model="shippingInfo.recmanname"
					placeholder="请输入收货人姓名"
					:border="true"
				></tn-input>
			</view>
			<view class="form-item">
				<text class="label">收货电话</text>
				<tn-input
					v-model="shippingInfo.recmanmobile"
					placeholder="请输入收货电话"
					:border="true"
				></tn-input>
			</view>
			<view class="form-item">
				<text class="label">收货地址</text>
				<tn-input
					v-model="shippingInfo.recmanaddress"
					placeholder="请输入收货地址"
					:border="true"
				></tn-input>
			</view>
			<view class="form-buttons">
				<tn-button @click="showShippingPopup = false">取消</tn-button>
				<tn-button type="primary" @click="confirmShipping">保存</tn-button>
			</view>
		</view>
	</tn-popup>
	
	<!-- 商品明细弹出层 -->
	<tn-popup v-model="showDetailsPopup" mode="center">
		<view class="details-popup">
			
			<z-paging ref="detailsPaging" v-model="detailsList" @query="queryDetails">
				<template #top>
					<view class="details-header">
						<text class="details-title">商品明细</text>
						<tn-button icon="close" size="sm" @click="showDetailsPopup = false"></tn-button>
					</view>
				</template>
				<view class="details-list">
					<view class="details-item" v-for="(detail, index) in detailsList" :key="index">
						<view class="detail-header">
							<text class="item-number">{{detail.billsn}}</text>
							<text class="item-name">{{detail.goodsname}}</text>
						</view>
						<view class="detail-content">
							<view class="detail-row">
								<text class="detail-value">{{detail.goodscode}}</text>
							</view>
							<view class="detail-row">
								<text class="detail-value">{{detail.goodsspec}}</text>
							</view>
							<view class="detail-row">
								<text class="detail-value">{{detail.manufacturer}}</text>
							</view>
							<view class="detail-row">
								<text class="detail-value">{{detail.batchinfo}}</text>
							</view>
							<view class="detail-row">
								<text class="detail-value">{{detail.taxprice}}</text>
							</view>
							<view class="detail-row">
								<text class="detail-value">{{detail.num}}</text>
							</view>
							<view class="detail-row">
								<text class="detail-value">{{detail.taxamount}}</text>
							</view>
							
						</view>
					</view>
				</view>
			</z-paging>
		</view>
	</tn-popup>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { formatDate } from '@/utils/date.js'
import { postCall } from '@/api/index.js'
import { createParams } from '@/utils/utils.js'
import dayjs from "dayjs"
import { toastMessage } from '@/utils/toast.js'

const beforeBack = () => {
	  return new Promise((resolve) => {
	    setTimeout(() => {
	      uni.redirectTo({
	      	url: '/pages/index/index'
	      });
		  return true;
	    }, 1000)
	  })
	}
// 搜索关键词
const searchKeyword = ref('')
const dataInfo = reactive({
	"startDate": "2024-01-01",
	"endDate": "2024-04-31"
})

// 日期选择
const selectDate = ref('')
const showCalendarPopup = ref(false)

// 分页相关
const paging = ref(null)
const recordList = ref([])

// 批量选择相关
const selectedCount = computed(() => {
	return recordList.value.filter(item => item.sel===1).length
})

const canShip = computed(() => {
	return selectedCount.value > 0 && recordList.value.some(item => item.sel===1)
})

// 打开日历弹窗
const openCalendarPopup = () => {
	showCalendarPopup.value = true
}

// 关闭日历弹窗并更新日期
const closeCalendarPopupPage = () => {
	showCalendarPopup.value = false
	console.log(selectDate.value)
	let date = {
		"startDate": dayjs(selectDate.value[0]).format('YYYY-MM-DD'),
		"endDate": dayjs(selectDate.value[1]).format('YYYY-MM-DD')
	}
	Object.assign(dataInfo, date)
	paging.value.reload()
}

// 处理搜索
const handleSearch = () => {
	paging.value.reload()
}

// 处理清除搜索
const handleClear = () => {
	searchKeyword.value = ''
	paging.value.reload()
}

// 处理复选框变化
const handleCheckboxChange = () => {
	// 可以在这里添加额外的逻辑
}

// 收货信息相关
const showShippingPopup = ref(false)
const shippingInfo = reactive({
	recmanname: '',
	recmanmobile: '',
	recmanaddress: ''
})

// 修改原来的handleBatchShip为实际的保存逻辑
const handleBatchShip = async () => {
	try {
		const selectedItems = recordList.value.filter(item => item.sel===1 );
		postCall(Object.assign( {
			"P_PROC_NAME": "PROC_APP_DO_HDXF",
			"P_ACTION": "SAVE",
			"P_IDS": selectedItems.map(item => item.id).join(',')
		},createParams(shippingInfo))).then(res=>{
			if(res){
				if(res.code===200 || res.code===1000){
					toastMessage("下发成功");
					showShippingPopup.value = false;
					// 重置表单
					Object.assign(shippingInfo, {
						receiver: '',
						phone: '',
						address: ''
					});
					setTimeout(() => {
						paging.value.reload();
					}, 1000)
				}else{
					toastMessage("下发失败");
				}
			}	
		})
	} catch (error) {
		toastMessage("下发失败");
	}
}

// 显示收货信息弹出层
const showShippingForm = () => {
	showShippingPopup.value = true
}

// 确认收货信息
const confirmShipping = () => {
	
	handleBatchShip();
}

let pageInfo = {
	P_PAGE : 1 ,
	P_PAGESIZE : 10
}
// 查询列表数据
const queryList = async (pageNo, pageSize) => {
	pageInfo.P_PAGE = pageNo;
	pageInfo.P_PAGESIZE = pageSize;
	let params = {};
	params["P_PROC_NAME"] = "PROC_APP_DO_HDXF";
	params["P_ACTION"] = 'GETBILLINFO';
	params["P_CON"] = searchKeyword.value;
	postCall(Object.assign(Object.assign(params,createParams(dataInfo)),pageInfo)).then(res=>{
		if(res){
			if(res.code===200 || res.code===1000){
				paging.value.complete(res.data.DATASET);
			}
		}
	  
	}).catch(res =>{
		paging.value.complete(false);
	})
}

// 商品明细相关
const showDetailsPopup = ref(false)
const detailsPaging = ref(null)
const detailsList = ref([])
const currentBillId = ref('')

// 显示明细
const showDetails = (item) => {
	currentBillId.value = item.id
	showDetailsPopup.value = true
	detailsPaging.value?.reload()
}

// 查询明细数据
const queryDetails = async (pageNo, pageSize) => {
	let params = {
		"P_PROC_NAME": "PROC_APP_DO_HDXF",
		"P_ACTION": 'GETBILLDETAIL',
		"P_ID": currentBillId.value,
		"P_PAGE": pageNo,
		"P_PAGESIZE": pageSize
	}
	
	try {
		const res = await postCall(params)
		if (res && (res.code === 200 || res.code === 1000)) {
			detailsPaging.value.complete(res.data.DATASET)
		} else {
			detailsPaging.value.complete(false)
		}
	} catch (error) {
		detailsPaging.value.complete(false)
	}
}

onMounted(() => {
	const firstDayOfMonth = dayjs().startOf('month')
	let date = {
		"startDate": firstDayOfMonth.format('YYYY-MM-DD'),
		"endDate": dayjs().format("YYYY-MM-DD")
	}
	Object.assign(dataInfo, date)
})
</script>

<style lang="scss">
.batch-ship-container {
	min-height: 100vh;
	background-color: #f8f8f8;
}

.search-section {
	padding-top: 20rpx;
	padding-left: 20rpx;
	padding-right: 20rpx;
	background-color: #fff;
}

.record-list {
	padding: 20rpx;
	padding-bottom: 120rpx;
	// background-color: #f8f8f8;
}

.record-item {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.record-header {
	display: flex;
	align-items: flex-start;
	
	.checkbox-wrapper {
		margin-right: 20rpx;
		padding-top: 8rpx;
	}
	
	.order-info {
		flex: 1;
		
		.order-top {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;
			
			.order-left {
				display: flex;
				align-items: center;
				
				.agent-name {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
					margin-right: 20rpx;
					line-height: 1;
				}
				
				.order-time {
					font-size: 24rpx;
					color: #999;
					line-height: 1;
				}
			}
			
			.order-right {
				text-align: right;
				
				.order-amount {
					font-size: 32rpx;
					color: #ff4d4f;
					font-weight: bold;
					display: block;
					line-height: 1;
				}
				
				.order-status {
					font-size: 24rpx;
					color: #ff4d4f;
					
					&.status-success {
						color: #52c41a;
					}
				}
			}
		}
		
		.order-middle {
			display: flex;
			margin-bottom: 16rpx;
			
			.order-no, .product-count {
				margin-right: 30rpx;
				
				.label {
					font-size: 26rpx;
					color: #999;
				}
				
				.value {
					font-size: 26rpx;
					color: #333;
				}
			}
		}
		
		.order-customer {
			margin-bottom: 16rpx;
			padding-bottom: 16rpx;
			border-bottom: 1rpx solid #f5f5f5;
			
			.label {
				font-size: 26rpx;
				color: #999;
			}
			
			.value {
				font-size: 26rpx;
				color: #333;
				font-weight: 500;
			}
		}
		
		.order-address {
			.label {
				font-size: 26rpx;
				color: #999;
			}
			
			.value {
				font-size: 26rpx;
				color: #333;
				line-height: 1.4;
			}
		}
	}
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #fff;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.selected-info {
		font-size: 28rpx;
		color: #666;
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
		
		.tn-button {
			height: 72rpx;
			line-height: 72rpx;
			padding: 0 40rpx;
			font-size: 28rpx;
		}
	}
}

.date-range {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0rpx;
	background: #fff;
	border-bottom: 2rpx solid #f0f0f0;
}

.date-picker-title {
	display: flex;
	align-items: center;
}

.picker-text {
	margin-left: 12rpx;
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}

.date-text {
	color: #666;
	font-size: 28rpx;
}

.popup-calendar-button {
	margin: 0 30rpx;
	width: calc(100% - 60rpx) !important;
	padding: 20rpx 30rpx !important;
}

.popup-class {
	border-radius: 20rpx 20rpx 0 0;
	overflow: hidden;
}

.calendar-class {
	height: 100% !important;
	margin-top: 30rpx;
}

.shipping-form {
	background-color: #fff;
	border-radius: 24rpx;
	padding: 40rpx;
	width: 600rpx;
	
	.form-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 40rpx;
	}
	
	.form-item {
		margin-bottom: 30rpx;
		
		.label {
			display: block;
			font-size: 28rpx;
			color: #333;
			margin-bottom: 16rpx;
		}
		
		.tn-input {
			width: 100%;
		}
	}
	
	.form-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
		gap: 20rpx;
		
		.tn-button {
			flex: 1;
		}
	}
}

.order-actions {
	margin-top: 16rpx;
	display: flex;
	justify-content: flex-end;
}

.details-popup {
	background-color: #fff;
	border-radius: 16rpx;
	width: 720rpx;
	max-height: 85vh;
	height: 85vh;
	
	.details-header {
		padding: 32rpx;
		border-bottom: 1rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
		
		.details-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.details-list {
		padding: 24rpx;
	}
	
	.details-item {
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		
		.detail-header {
			padding: 24rpx;
			background-color: #f8f9fa;
			border-bottom: 1rpx solid #eee;
			display: flex;
			align-items: center;
			
			.item-number {
				background-color: var(--tn-color-primary);
				color: #fff;
				padding: 4rpx 16rpx;
				border-radius: 6rpx;
				font-size: 24rpx;
				margin-right: 16rpx;
			}
			
			.item-name {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				font-weight: bold;
			}
		}
		
		.detail-content {
			padding: 24rpx;
		}
		
		.detail-row {
			display: flex;
			margin-bottom: 16rpx;
			align-items: center;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.detail-label {
				width: 140rpx;
				color: #666;
				font-size: 26rpx;
				flex-shrink: 0;
			}
			
			.detail-value {
				flex: 1;
				color: #333;
				font-size: 26rpx;
			}
		}
		
		.detail-info {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			margin-top: 20rpx;
			padding: 20rpx 24rpx;
			background-color: #f8f9fa;
			border-radius: 8rpx;
			gap: 32rpx;
			
			.info-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				
				.info-label {
					font-size: 24rpx;
					color: #666;
					margin-bottom: 4rpx;
				}
				
				.info-value {
					font-size: 28rpx;
					
					&.price {
						color: #333;
						font-weight: 500;
					}
					
					&.quantity {
						color: #333;
					}
					
					&.amount {
						color: #ff6b6b;
						font-weight: bold;
						font-size: 32rpx;
					}
				}
			}
		}
	}
}
</style> 